/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState } from 'react';
import { Button, Space, Tag, Popconfirm, message, Image } from 'antd';
import { getProductList, essayTop, essayOnline, essayDelete } from '@/services/news/product';
import KbPreviewModal from '../components/KbPreviewModal';
import type { PublishItem } from '../utils';
import type { ActionType } from '@ant-design/pro-table';
import { history } from 'umi';
import { ProList } from '@ant-design/pro-list';
import styles from './index.less';

const Index = () => {
  const actionRef = useRef<ActionType>();
  const [visible, setVisible] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<PublishItem>();

  const handleOpenPreViewModal = (record: PublishItem) => {
    setDataSource(record);
    setVisible(true);
  };
  const handleClosePreViewModal = () => {
    setDataSource(undefined);
    setVisible(false);
  };
  const handleSetTop = (record_: any) => {
    const { id, top } = record_;
    essayTop({ id, top: `${top}` === '1' ? '0' : '1' }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('操作成功');
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };
  const handleOnline = (record_: any) => {
    const { id, status } = record_;
    essayOnline({ id, status: status === '1' ? '0' : '1' }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('操作成功');
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };
  const handleDelete = (id: string) => {
    essayDelete({ id }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };
  const handleAdd = (id?: string) => {
    const query: {
      id?: string;
    } = {
      id,
    };
    history.push({
      pathname: '/f/news/product/details',
      query,
    });
  };
  const getList = async (values: any) => {
    const { current: page, pageSize: size, ...rest } = values;
    return getProductList({ ...rest, page, size, status: 1 }).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        const { list, count: total } = data;
        return {
          total,
          data: list,
        };
      } else {
        message.error(msg);
        return {};
      }
    });
  };
  return (
    <>
      <ProList
        className={styles.productPublish}
        actionRef={actionRef}
        toolbar={{
          settings: [
            <Button key='3' type='primary' onClick={handleAdd.bind(null, '')}>
              发布
            </Button>,
          ],
        }}
        search={{}}
        rowKey='name'
        request={getList}
        itemLayout='vertical'
        pagination={{
          pageSize: 20,
        }}
        metas={{
          search: {
            fieldProps: {
              placeholder: '请输入标题搜索',
            },
          },
          title: {
            search: false,
          },
          description: {
            search: false,
            render: (_, record: PublishItem) => {
              const { category, tag, update_time } = record;
              return (
                <Space wrap>
                  <div>{category}</div>
                  {category ? '|' : null}
                  {tag?.map((item: string, index: number) => (
                    <Tag color='processing' key={item + index}>
                      {item}
                    </Tag>
                  ))}
                  <div>{update_time}</div>
                </Space>
              );
            },
          },
          actions: {
            render: (_, record: PublishItem) => {
              const { id, read_count, top, status } = record;
              const topTxt = `${top}` === '1' ? '取消置顶' : '置顶';
              const onlineTxt = status == '1' ? '下线' : '上线';
              return (
                <Space wrap align='start' size='large'>
                  <div>阅读：{read_count}</div>
                  <Popconfirm
                    title={`你确定${topTxt}吗？`}
                    onConfirm={handleSetTop.bind(null, record)}
                  >
                    <a>{topTxt}</a>
                  </Popconfirm>
                  <Popconfirm
                    title={`你确定${onlineTxt}吗？`}
                    onConfirm={handleOnline.bind(null, record)}
                  >
                    <a>{onlineTxt}</a>
                  </Popconfirm>
                  <Popconfirm title={`你确定删除吗？`} onConfirm={handleDelete.bind(null, id)}>
                    <a>删除</a>
                  </Popconfirm>
                  {onlineTxt === '上线' && <a onClick={handleAdd.bind(null, id)}>编辑</a>}
                  <a onClick={handleOpenPreViewModal.bind(null, record)}>预览</a>
                </Space>
              );
            },
          },
          extra: {
            search: false,
            render: (_: any, record: PublishItem) => {
              const { picture } = record;
              return (
                <>{picture && <Image preview={false} width={125} alt='logo' src={picture} />}</>
              );
            },
          },
        }}
      ></ProList>
      <KbPreviewModal content={dataSource} visible={visible} onCancel={handleClosePreViewModal} />
    </>
  );
};

export default Index;
